<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记录</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <script>
        // 格式化日期时间函数
        function formatDateTime(dateString) {
            try {
                const date = new Date(dateString);
                if (isNaN(date.getTime())) {
                    throw new Error('Invalid date');
                }
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${year}-${month}-${day}T${hours}:${minutes}`;
            } catch (error) {
                console.error('Error formatting date:', error);
                const now = new Date();
                return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}T${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
            }
        }
        
        // 显示编辑模态框
        function showEditModal(matchId) {
            selectedMatchId = matchId;
            const match = allMatches.find(m => m.id === matchId);
            
            if (!match) return;
            
            // 加载战队和联赛数据
            loadTeamsDataForEdit().then(() => {
                // 填充表单
                document.getElementById('edit_match_id').value = match.id;
                
                // 设置赛制
                const formatSelect = document.getElementById('edit_match_format');
                for (let i = 0; i < formatSelect.options.length; i++) {
                    if (formatSelect.options[i].value === match.match_format) {
                        formatSelect.selectedIndex = i;
                        break;
                    }
                }
                
                // 格式化日期时间
                const matchDate = new Date(match.match_date);
                const formattedDateTime = formatDateTime(matchDate);
                document.getElementById('edit_match_date').value = formattedDateTime;
                
                // 提取团队所属的联赛
                let team1League = '';
                let team2League = '';
                
                for (const league of allTeams) {
                    const team1Found = league.teams.find(t => t.name === match.team1);
                    const team2Found = league.teams.find(t => t.name === match.team2);
                    
                    if (team1Found) team1League = league.league;
                    if (team2Found) team2League = league.league;
                    
                    if (team1League && team2League) break;
                }
                
                // 设置联赛 (使用第一队的联赛)
                const leagueSelect = document.getElementById('edit_league');
                if (team1League) {
                    for (let i = 0; i < leagueSelect.options.length; i++) {
                        if (leagueSelect.options[i].value === team1League) {
                            leagueSelect.selectedIndex = i;
                            break;
                        }
                    }
                    loadTeamsByLeagueForEdit(team1League);
                }
                
                // 设置主队方位
                const team1BlueSideSelect = document.getElementById('edit_team1_blue_side');
                team1BlueSideSelect.value = match.team1_blue_side === true ? 'true' : 'false';
                
                // 设置其他字段
                document.getElementById('edit_investment').value = match.investment;
                document.getElementById('edit_return_amount').value = match.return_amount;
                
                // 清空游戏详情容器
                document.getElementById('editGamesContainer').innerHTML = '';
                
                // 添加已有的游戏详情
                if (match.games && match.games.length > 0) {
                    match.games.forEach((game, index) => {
                        const fieldId = Date.now() + index;
                        const gameField = document.createElement('div');
                        gameField.className = 'game-field bg-gray-50 p-3 rounded-md mb-3';
                        gameField.innerHTML = `
                            <div class="flex items-center justify-between mb-2">
                                <h3 class="text-sm font-medium">第${game.game_number}局比赛</h3>
                                <button type="button" onclick="removeEditGameField(this)" class="text-red-500 text-xs">
                                    <i class="fas fa-times"></i> 移除
                                </button>
                            </div>
                            <div class="grid grid-cols-2 gap-2">
                                <div class="input-group">
                                    <select name="edit_game_blue_side_${fieldId}" id="edit_game_blue_side_${fieldId}" required class="text-xs py-2">
                                        <option value="true" ${game.blue_side ? 'selected' : ''}>主队蓝方</option>
                                        <option value="false" ${!game.blue_side ? 'selected' : ''}>主队红方</option>
                                    </select>
                                    <label for="edit_game_blue_side_${fieldId}" class="text-xs">方位</label>
                                </div>
                                <div class="input-group">
                                    <input type="number" name="edit_game_number_${fieldId}" id="edit_game_number_${fieldId}" value="${game.game_number}" placeholder=" " required class="text-xs py-2">
                                    <label for="edit_game_number_${fieldId}" class="text-xs">局数</label>
                                </div>
                                <div class="input-group">
                                    <select name="edit_game_winner_side_${fieldId}" id="edit_game_winner_side_${fieldId}" required class="text-xs py-2">
                                        <option value="blue" ${game.winner_side === 'blue' ? 'selected' : ''}>蓝方获胜</option>
                                        <option value="red" ${game.winner_side === 'red' ? 'selected' : ''}>红方获胜</option>
                                    </select>
                                    <label for="edit_game_winner_side_${fieldId}" class="text-xs">获胜方</label>
                                </div>
                                <div class="input-group">
                                    <input type="number" name="edit_game_investment_${fieldId}" id="edit_game_investment_${fieldId}" value="${game.investment}" placeholder=" " required class="text-xs py-2">
                                    <label for="edit_game_investment_${fieldId}" class="text-xs">投资额</label>
                                </div>
                                <div class="input-group">
                                    <input type="number" name="edit_game_return_${fieldId}" id="edit_game_return_${fieldId}" value="${game.return_amount}" placeholder=" " required class="text-xs py-2">
                                    <label for="edit_game_return_${fieldId}" class="text-xs">回报额</label>
                                </div>
                            </div>
                            <input type="hidden" name="edit_game_id_${fieldId}" id="edit_game_id_${fieldId}" value="${fieldId}">
                        `;
                        
                        document.getElementById('editGamesContainer').appendChild(gameField);
                    });
                }
                
                // 延迟设置团队和获胜方 (等待联赛加载完成)
                setTimeout(() => {
                    const team1Select = document.getElementById('edit_team1');
                    const team2Select = document.getElementById('edit_team2');
                    
                    // 设置主队
                    for (let i = 0; i < team1Select.options.length; i++) {
                        if (team1Select.options[i].value === match.team1) {
                            team1Select.selectedIndex = i;
                            break;
                        }
                    }
                    
                    // 设置客队
                    for (let i = 0; i < team2Select.options.length; i++) {
                        if (team2Select.options[i].value === match.team2) {
                            team2Select.selectedIndex = i;
                            break;
                        }
                    }
                    
                    // 更新获胜方选项
                    updateEditWinnerOptions();
                    
                    // 设置获胜方
                    const winnerSelect = document.getElementById('edit_winner');
                    for (let i = 0; i < winnerSelect.options.length; i++) {
                        if (winnerSelect.options[i].value === match.winner) {
                            winnerSelect.selectedIndex = i;
                            break;
                        }
                    }
                }, 100);
            });
            
            const modal = document.getElementById('editMatchModal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            setTimeout(() => {
                modal.classList.add('modal-show');
            }, 10);
        }
    </script>
    <style>
        .modal-backdrop {
            backdrop-filter: blur(5px);
            transition: all 0.3s ease;
        }
        .modal-content {
            transform: scale(0.9);
            opacity: 0;
            transition: all 0.3s ease;
        }
        .modal-show .modal-content {
            transform: scale(1);
            opacity: 1;
        }
        .input-group {
            position: relative;
            margin-bottom: 1.5rem;
        }
        .input-group input, .input-group select {
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #e5e7eb;
            border-radius: 0.5rem;
            font-size: 1rem;
            line-height: 1.5;
            transition: all 0.3s;
            background-color: #f9fafb;
        }
        .input-group input:focus, .input-group select:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
            background-color: white;
        }
        .input-group label {
            position: absolute;
            left: 1rem;
            top: 0.75rem;
            color: #6b7280;
            transition: all 0.3s;
            pointer-events: none;
            z-index: 1;
        }
        .input-group input:focus + label,
        .input-group input:not(:placeholder-shown) + label,
        .input-group select:focus + label,
        .input-group select:not([value=""]):not(:focus) + label {
            top: -0.5rem;
            left: 0.75rem;
            font-size: 0.75rem;
            padding: 0 0.25rem;
            background-color: white;
            color: #3b82f6;
        }
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 500;
            transition: all 0.3s;
        }
        .btn-primary {
            background-color: #3b82f6;
            color: white;
        }
        .btn-primary:hover {
            background-color: #2563eb;
        }
        .btn-secondary {
            background-color: white;
            border: 1px solid #e5e7eb;
            color: #4b5563;
        }
        .btn-secondary:hover {
            background-color: #f9fafb;
        }
        .btn-danger {
            background-color: #ef4444;
            color: white;
        }
        .btn-danger:hover {
            background-color: #dc2626;
        }
        .filter-btn {
            transition: all 0.3s;
        }
        .filter-btn.active {
            background-color: #3b82f6;
            color: white;
        }
        .record-card {
            transition: all 0.2s;
        }
        .record-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        .profit-positive {
            color: #10b981;
            background-color: rgba(16, 185, 129, 0.1);
            border-radius: 0.5rem;
            padding: 0.25rem 0.5rem;
            font-weight: 500;
        }
        .profit-negative {
            color: #ef4444;
            background-color: rgba(239, 68, 68, 0.1);
            border-radius: 0.5rem;
            padding: 0.25rem 0.5rem;
            font-weight: 500;
        }
        .context-menu {
            position: fixed;
            z-index: 1000;
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            overflow: hidden;
        }
        .context-menu-item {
            padding: 0.75rem 1.5rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .context-menu-item:hover {
            background-color: #f3f4f6;
        }
        .context-menu-item.danger:hover {
            background-color: #fee2e2;
            color: #ef4444;
        }
        .team-icon {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            object-fit: cover;
            border: 1px solid #e5e7eb;
            background-color: #000000;
            padding: 2px;
        }
        
        .match-vs {
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 0 8px;
        }
        
        .match-vs::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background-color: #e5e7eb;
            z-index: 0;
        }
        
        .vs-text {
            background-color: white;
            padding: 0 6px;
            z-index: 1;
            font-size: 10px;
            color: #9ca3af;
        }
        
        .winner-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background-color: #10b981;
            border-radius: 50%;
            width: 16px;
            height: 16px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 8px;
            border: 1px solid white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .winner-team {
            background-color: rgba(16, 185, 129, 0.08);
            border: 1px solid rgba(16, 185, 129, 0.3);
            border-radius: 0.5rem;
            padding: 3px 5px;
            transform: scale(1.05);
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }
        
        .match-format-badge {
            font-size: 9px;
            padding: 1px 4px;
            border-radius: 4px;
            background-color: #f3f4f6;
            color: #6b7280;
        }
        
        .blue-side {
            background-color: rgba(37, 99, 235, 0.1);
            border-left: 2px solid #3b82f6;
        }
        
        .red-side {
            background-color: rgba(220, 38, 38, 0.1);
            border-left: 2px solid #ef4444;
        }
        
        .game-detail-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 4px 8px;
            margin-bottom: 4px;
            border-radius: 4px;
            font-size: 10px;
        }
        
        .game-detail-container {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease;
        }
        
        .game-detail-container.show {
            max-height: 300px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <div class="max-w-md mx-auto h-screen flex flex-col">
        <!-- 顶部导航 -->
        <header class="bg-white shadow-sm">
            <div class="px-4 py-6">
                <div class="flex justify-between items-center">
                    <h1 class="text-xl font-semibold">记录</h1>
                    <button onclick="showAddMatchModal()" class="bg-blue-500 text-white rounded-full w-10 h-10 flex items-center justify-center shadow-lg hover:bg-blue-600 transition">
                        <i class="fas fa-plus"></i>
                    </button>
                </div>
                <!-- 快速筛选 -->
                <div class="flex gap-2 mt-4 overflow-x-auto pb-2">
                    <button onclick="filterMatches('all')" class="filter-btn active px-4 py-2 bg-blue-100 text-blue-600 rounded-full text-sm whitespace-nowrap shadow-sm">
                        全部
                    </button>
                    <button onclick="filterMatches('profit')" class="filter-btn px-4 py-2 bg-green-50 text-green-600 rounded-full text-sm whitespace-nowrap shadow-sm">
                        盈利
                    </button>
                    <button onclick="filterMatches('loss')" class="filter-btn px-4 py-2 bg-red-50 text-red-600 rounded-full text-sm whitespace-nowrap shadow-sm">
                        亏损
                    </button>
                    <button onclick="filterMatches('week')" class="filter-btn px-4 py-2 bg-gray-100 text-gray-600 rounded-full text-sm whitespace-nowrap shadow-sm">
                        本周
                    </button>
                    <button onclick="filterMatches('month')" class="filter-btn px-4 py-2 bg-gray-100 text-gray-600 rounded-full text-sm whitespace-nowrap shadow-sm">
                        本月
                    </button>
                </div>
            </div>
        </header>

        <!-- 记录列表 -->
        <div class="flex-1 overflow-y-auto">
            <div id="matchList" class="p-4 space-y-4">
                <!-- 记录卡片将通过JavaScript动态添加 -->
            </div>
        </div>

        <!-- 底部导航 -->
        <nav class="bg-white border-t border-gray-200">
            <div class="flex justify-around py-3">
                <a href="home.html" class="flex flex-col items-center text-blue-500">
                    <i class="fas fa-list-ul"></i>
                    <span class="text-xs mt-1">记录</span>
                </a>
                <a href="zhandui.html" class="flex flex-col items-center text-gray-400">
                    <i class="fas fa-users"></i>
                    <span class="text-xs mt-1">战队</span>
                </a>
                <a href="stats.html" class="flex flex-col items-center text-gray-400">
                    <i class="fas fa-chart-bar"></i>
                    <span class="text-xs mt-1">统计</span>
                </a>
            </div>
        </nav>

        <!-- 添加记录模态框 -->
        <div id="addMatchModal" class="fixed inset-0 bg-black bg-opacity-40 modal-backdrop hidden items-start justify-center z-50 overflow-y-auto pt-4 pb-4">
            <div class="modal-content bg-white rounded-xl p-4 w-11/12 max-w-md shadow-2xl my-4 relative max-h-[90vh] flex flex-col">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">添加记录</h2>
                    <button onclick="hideAddMatchModal()" class="text-gray-400 hover:text-gray-600 transition">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="addMatchForm" class="overflow-y-auto flex-1 px-1">
                    <div class="space-y-5 pb-20 pt-5">
                        <div class="input-group">
                            <select name="league" id="league" onchange="loadTeamsByLeague(this.value)" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="league">联赛</label>
                        </div>
                        <div class="input-group">
                            <select name="team1" id="team1" onchange="updateWinnerOptions()" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="team1">主队</label>
                        </div>
                        <div class="input-group">
                            <select name="team2" id="team2" onchange="updateWinnerOptions()" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="team2">客队</label>
                        </div>
                        <div class="input-group">
                            <select name="winner" id="winner" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="winner">获胜方</label>
                        </div>
                        <div class="input-group">
                            <select name="match_format" id="match_format" required>
                                <option value="Bo3" selected>Bo3</option>
                                <option value="Bo5">Bo5</option>
                            </select>
                            <label for="match_format">赛制</label>
                        </div>
                        <div class="input-group">
                            <select name="team1_blue_side" id="team1_blue_side" required>
                                <option value="true" selected>主队蓝方</option>
                                <option value="false">主队红方</option>
                            </select>
                            <label for="team1_blue_side">主队方位</label>
                        </div>
                        <div class="input-group">
                            <input type="number" name="investment" id="investment" placeholder=" " required>
                            <label for="investment">总投资额</label>
                        </div>
                        <div class="input-group">
                            <input type="number" name="return_amount" id="return_amount" placeholder=" " required>
                            <label for="return_amount">总回报额</label>
                        </div>
                        <div class="input-group">
                            <input type="datetime-local" name="match_date" id="match_date" placeholder=" " required>
                            <label for="match_date">比赛日期</label>
                        </div>
                        
                        <div class="border-t border-gray-200 pt-4">
                            <div class="flex justify-between items-center mb-2">
                                <h3 class="text-sm font-medium">单场比赛详情(可选)</h3>
                                <button type="button" onclick="addGameField()" class="text-blue-500 text-sm">
                                    <i class="fas fa-plus"></i> 添加
                                </button>
                            </div>
                            <div id="gamesContainer" class="space-y-2">
                                <!-- 游戏字段将动态添加到这里 -->
                            </div>
                        </div>
                    </div>
                </form>
                <div class="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 rounded-b-xl flex justify-end space-x-3">
                    <button type="button" onclick="hideAddMatchModal()" class="btn btn-secondary">取消</button>
                    <button type="submit" form="addMatchForm" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>

        <!-- 编辑记录模态框 -->
        <div id="editMatchModal" class="fixed inset-0 bg-black bg-opacity-40 modal-backdrop hidden items-start justify-center z-50 overflow-y-auto pt-4 pb-4">
            <div class="modal-content bg-white rounded-xl p-4 w-11/12 max-w-md shadow-2xl my-4 relative max-h-[90vh] flex flex-col">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-xl font-semibold text-gray-800">编辑记录</h2>
                    <button onclick="hideEditModal()" class="text-gray-400 hover:text-gray-600 transition">
                        <i class="fas fa-times text-xl"></i>
                    </button>
                </div>
                <form id="editMatchForm" class="overflow-y-auto flex-1 px-1">
                    <div class="space-y-5 pb-20 pt-5">
                        <input type="hidden" id="edit_match_id" name="id">
                        
                        <div class="input-group">
                            <select name="league" id="edit_league" onchange="loadTeamsByLeagueForEdit(this.value)" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="edit_league">联赛</label>
                        </div>
                        <div class="input-group">
                            <select name="team1" id="edit_team1" onchange="updateEditWinnerOptions()" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="edit_team1">主队</label>
                        </div>
                        <div class="input-group">
                            <select name="team2" id="edit_team2" onchange="updateEditWinnerOptions()" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="edit_team2">客队</label>
                        </div>
                        <div class="input-group">
                            <select name="winner" id="edit_winner" required>
                                <option value="" selected disabled hidden></option>
                            </select>
                            <label for="edit_winner">获胜方</label>
                        </div>
                        <div class="input-group">
                            <select name="match_format" id="edit_match_format" required>
                                <option value="Bo3">Bo3</option>
                                <option value="Bo5">Bo5</option>
                            </select>
                            <label for="edit_match_format">赛制</label>
                        </div>
                        <div class="input-group">
                            <select name="team1_blue_side" id="edit_team1_blue_side" required>
                                <option value="true">蓝色方</option>
                                <option value="false">红色方</option>
                            </select>
                            <label for="edit_team1_blue_side">主队方位</label>
                        </div>
                        <div class="input-group">
                            <input type="number" name="investment" id="edit_investment" placeholder=" " required>
                            <label for="edit_investment">总投资额</label>
                        </div>
                        <div class="input-group">
                            <input type="number" name="return_amount" id="edit_return_amount" placeholder=" " required>
                            <label for="edit_return_amount">总回报额</label>
                        </div>
                        <div class="input-group">
                            <input type="datetime-local" name="match_date" id="edit_match_date" placeholder=" " step="60" required pattern="\d{4}-\d{2}-\d{2}T\d{2}:\d{2}">
                            <label for="edit_match_date">比赛日期</label>
                        </div>
                        
                        <div class="border-t border-gray-200 pt-4">
                            <div class="flex justify-between items-center mb-2">
                                <h3 class="text-sm font-medium">单场比赛详情</h3>
                                <button type="button" onclick="addEditGameField()" class="text-blue-500 text-sm">
                                    <i class="fas fa-plus"></i> 添加
                                </button>
                            </div>
                            <div id="editGamesContainer" class="space-y-2">
                                <!-- 游戏字段将动态添加到这里 -->
                            </div>
                        </div>
                    </div>
                </form>
                <div class="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 rounded-b-xl flex justify-end space-x-3">
                    <button type="button" onclick="deleteMatch()" class="btn bg-red-500 text-white">删除</button>
                    <button type="button" onclick="hideEditModal()" class="btn btn-secondary">取消</button>
                    <button type="submit" form="editMatchForm" class="btn btn-primary">保存</button>
                </div>
            </div>
        </div>

        <!-- 添加确认删除弹窗 -->
        <div id="confirmDeleteModal" class="fixed inset-0 bg-black bg-opacity-40 modal-backdrop hidden items-center justify-center z-50">
            <div class="modal-content bg-white rounded-xl p-6 w-11/12 max-w-sm shadow-2xl">
                <div class="text-center">
                    <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-exclamation-triangle text-red-500 text-xl"></i>
                    </div>
                    <h3 class="text-lg font-medium text-gray-900 mb-2">确定删除这条记录吗？</h3>
                    <p class="text-sm text-gray-500 mb-6">此操作不可撤销。</p>
                    <div class="flex justify-center space-x-3">
                        <button type="button" onclick="hideConfirmDeleteModal()" class="btn btn-secondary">
                            取消
                        </button>
                        <button type="button" onclick="confirmDelete()" class="btn btn-danger">
                            确定删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // API基础URL
        const API_BASE_URL = window.location.origin + '/api';
        
        // 全局变量
        let allTeams = []; // 按联赛分组的战队数据
        let allTeamsFlat = []; // 扁平的战队数据
        let allMatches = [];
        let selectedMatchId = null;
        let longPressTimer = null;
        
        // 格式化盈利/亏损显示
        function formatProfit(profit) {
            const absProfit = Math.abs(profit);
            const sign = profit >= 0 ? '+' : '-';
            return `${sign}${absProfit}`;
        }

        // 获取并显示比赛记录
        async function loadMatches() {
            try {
                const response = await fetch(`${API_BASE_URL}/matches`);
                allMatches = await response.json();
                renderMatches(allMatches);
            } catch (error) {
                console.error('Error loading matches:', error);
            }
        }
        
        // 渲染比赛记录列表
        function renderMatches(matches) {
            const matchList = document.getElementById('matchList');
            matchList.innerHTML = matches.map(match => {
                const profit = match.return_amount - match.investment;
                const isProfit = profit > 0;
                
                // 获取战队图标URL
                const team1Icon = getTeamIconUrl(match.team1);
                const team2Icon = getTeamIconUrl(match.team2);
                const isTeam1Winner = match.winner === match.team1;
                const isTeam2Winner = match.winner === match.team2;
                
                // 处理游戏详情
                const gamesDetail = match.games || [];
                
                const gameDetailsHTML = gamesDetail.map((game, index) => {
                    const blueTeam = game.blue_team || (game.blue_side ? match.team1 : match.team2);
                    const redTeam = game.red_team || (game.blue_side ? match.team2 : match.team1);
                    const gameProfit = game.return_amount - game.investment;
                    const isGameProfit = gameProfit > 0;
                    const blueTeamIcon = getTeamIconUrl(blueTeam);
                    const redTeamIcon = getTeamIconUrl(redTeam);
                    const winner = game.winner || match.winner;
                    const isBlueWinner = winner === blueTeam;
                    const isRedWinner = winner === redTeam;
                    
                    return `
                        <div class="game-detail mb-2 p-3 bg-gradient-to-r from-blue-50 to-red-50 rounded-lg shadow-md hover:shadow-lg transition-shadow duration-200">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center space-x-2 ${isBlueWinner ? 'text-blue-600 font-bold' : 'text-gray-600'}">
                                    <div class="w-8 h-8 relative">
                                        <img src="${blueTeamIcon}" alt="${blueTeam}" class="w-full h-full object-contain ${isBlueWinner ? 'ring-2 ring-blue-400 rounded-full' : ''}">
                                        ${isBlueWinner ? '<div class="absolute -top-1 -right-1 w-4 h-4 bg-blue-500 rounded-full flex items-center justify-center"><i class="fas fa-crown text-yellow-400 text-xs"></i></div>' : ''}
                                    </div>
                                    <span class="text-sm">${blueTeam}</span>
                                </div>
                                <div class="flex items-center space-x-2">
                                    <span class="text-xs font-medium px-2 py-1 rounded ${isGameProfit ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}">
                                        ${formatProfit(gameProfit)}
                                    </span>
                                    <span class="text-gray-400 text-sm">VS</span>
                                </div>
                                <div class="flex items-center space-x-2 ${isRedWinner ? 'text-red-600 font-bold' : 'text-gray-600'}">
                                    <span class="text-sm">${redTeam}</span>
                                    <div class="w-8 h-8 relative">
                                        <img src="${redTeamIcon}" alt="${redTeam}" class="w-full h-full object-contain ${isRedWinner ? 'ring-2 ring-red-400 rounded-full' : ''}">
                                        ${isRedWinner ? '<div class="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full flex items-center justify-center"><i class="fas fa-crown text-yellow-400 text-xs"></i></div>' : ''}
                                    </div>
                                </div>
                            </div>
                            <div class="mt-2 flex justify-between items-center text-xs text-gray-500">
                                <span>投资: ${game.investment || 0}</span>
                                <span>回报: ${game.return_amount || 0}</span>
                                <span class="px-2 py-1 rounded ${isGameProfit ? 'bg-green-50 text-green-600' : 'bg-red-50 text-red-600'}">
                                    盈亏: ${formatProfit(gameProfit)}
                                </span>
                            </div>
                        </div>
                    `;
                }).join('');
                
                // 计算总盈亏和胜负场次
                let totalWins = 0;
                let totalLosses = 0;
                let profitGames = 0;
                let lossGames = 0;
                let profitAmount = 0;
                let lossAmount = 0;

                gamesDetail.forEach(game => {
                    const gameProfit = game.return_amount - game.investment;
                    if (gameProfit > 0) {
                        profitGames++;
                        profitAmount += gameProfit;
                    } else {
                        lossGames++;
                        lossAmount += Math.abs(gameProfit);
                    }
                    
                    const isBlueWinner = game.winner_side === 'blue';
                    const winnerTeam = isBlueWinner ? game.blue_team : game.red_team;
                    if (winnerTeam === match.winner) {
                        totalWins++;
                    } else {
                        totalLosses++;
                    }
                });

                const summaryHTML = `
                <div class="mt-2 p-2 bg-gray-50 rounded-md text-xs">
                    <div class="flex justify-between items-center">
                        <div>
                            <span class="text-gray-500">胜负：</span>
                            <span class="text-green-500 font-medium">${totalWins}</span>
                            <span class="text-gray-500">/</span>
                            <span class="text-red-500 font-medium">${totalLosses}</span>
                        </div>
                        <div>
                            <span class="text-gray-500">盈亏场次：</span>
                            <span class="text-green-500 font-medium">${profitGames}</span>
                            <span class="text-gray-500">/</span>
                            <span class="text-red-500 font-medium">${lossGames}</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-center mt-1">
                        <div>
                            <span class="text-gray-500">盈利：</span>
                            <span class="text-green-500 font-medium">+${profitAmount.toFixed(0)}</span>
                        </div>
                        <div>
                            <span class="text-gray-500">亏损：</span>
                            <span class="text-red-500 font-medium">-${lossAmount.toFixed(0)}</span>
                        </div>
                    </div>
                </div>
                `;
                
                // 计算总局盈利和单局盈利总和
                const totalProfit = parseFloat(match.profit) || 0;
                const gamesProfit = gamesDetail.reduce((sum, game) => {
                    return sum + (parseFloat(game.return_amount) - parseFloat(game.investment));
                }, 0);
                const totalProfitWithGames = totalProfit + gamesProfit;

                return `
                <div class="record-card bg-white rounded-xl p-3 shadow-sm" 
                    data-id="${match.id}"
                    ontouchstart="startLongPress(event, ${match.id})" 
                    ontouchend="cancelLongPress()" 
                    ontouchmove="cancelLongPress()"
                    onmousedown="startLongPress(event, ${match.id})" 
                    onmouseup="cancelLongPress()" 
                    onmouseleave="cancelLongPress()">
                    <div class="flex justify-between items-center mb-2">
                        <div class="flex items-center gap-2">
                            <span class="match-format-badge">${match.match_format || 'Bo3'}</span>
                            <div class="text-xs text-gray-400">
                                ${match.match_date}
                            </div>
                        </div>
                        <div class="flex flex-col items-end">
                            <div class="${totalProfitWithGames > 0 ? 'text-green-500' : 'text-red-500'} text-sm font-medium">
                                ${totalProfitWithGames > 0 ? '+' : ''}${totalProfitWithGames.toFixed(0)}
                            </div>
                            <div class="text-xs text-gray-500">
                                总局: ${totalProfit > 0 ? '+' : ''}${totalProfit.toFixed(0)} 单局: ${gamesProfit > 0 ? '+' : ''}${gamesProfit.toFixed(0)}
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex justify-between items-center">
                        <div class="flex flex-col items-center w-5/12 ${isTeam1Winner ? 'winner-team' : ''}">
                            <div class="relative">
                                <img src="${team1Icon}" alt="${match.team1}" class="team-icon mx-auto mb-1">
                                ${isTeam1Winner ? '<div class="winner-badge"><i class="fas fa-trophy"></i></div>' : ''}
                                ${match.team1_blue_side ? '<span class="absolute -left-2 -bottom-1 text-xs text-blue-500"><i class="fas fa-square"></i></span>' : '<span class="absolute -left-2 -bottom-1 text-xs text-red-500"><i class="fas fa-square"></i></span>'}
                            </div>
                            <div class="text-center font-medium text-xs truncate w-full ${isTeam1Winner ? 'text-green-600' : ''}">${match.team1}</div>
                        </div>
                        
                        <div class="match-vs">
                            <span class="vs-text">VS</span>
                        </div>
                        
                        <div class="flex flex-col items-center w-5/12 ${isTeam2Winner ? 'winner-team' : ''}">
                            <div class="relative">
                                <img src="${team2Icon}" alt="${match.team2}" class="team-icon mx-auto mb-1">
                                ${isTeam2Winner ? '<div class="winner-badge"><i class="fas fa-trophy"></i></div>' : ''}
                                ${!match.team1_blue_side ? '<span class="absolute -right-2 -bottom-1 text-xs text-blue-500"><i class="fas fa-square"></i></span>' : '<span class="absolute -right-2 -bottom-1 text-xs text-red-500"><i class="fas fa-square"></i></span>'}
                            </div>
                            <div class="text-center font-medium text-xs truncate w-full ${isTeam2Winner ? 'text-green-600' : ''}">${match.team2}</div>
                        </div>
                    </div>
                    
                    ${gamesDetail.length > 0 ? `
                        <div class="mt-2 text-center">
                            <button type="button" class="text-xs text-blue-500" onclick="toggleGameDetails(event, ${match.id})">
                                <i class="fas fa-chevron-down"></i> 
                                查看详情
                            </button>
                            
                            <div id="gameDetails-${match.id}" class="game-detail-container mt-2">
                                ${gameDetailsHTML}
                                ${summaryHTML}
                            </div>
                        </div>
                    ` : ''}
                </div>
                `;
            }).join('');
        }

        // 获取战队图标
        function getTeamIconUrl(teamName) {
            // 默认图标
            let iconUrl = '/static/team_icons/default_team.png';
            
            // 在已加载的战队中查找对应图标
            if (allTeams && allTeams.length > 0) {
                // 检查是否是分组的数据结构
                if (allTeams[0].hasOwnProperty('teams')) {
                    // 分组结构
                    for (const league of allTeams) {
                        const team = league.teams.find(t => t.name === teamName);
                        if (team) {
                            iconUrl = team.icon;
                            break;
                        }
                    }
                } else {
                    // 扁平结构
                    const team = allTeams.find(t => t.name === teamName);
                    if (team) {
                        iconUrl = team.icon;
                    }
                }
            }
            
            return iconUrl;
        }

        // 长按开始
        function startLongPress(event, matchId) {
            longPressTimer = setTimeout(() => {
                showEditModal(matchId);
            }, 500); // 长按500毫秒触发
        }

        // 取消长按
        function cancelLongPress() {
            clearTimeout(longPressTimer);
        }

        // 隐藏编辑模态框
        function hideEditModal() {
            const modal = document.getElementById('editMatchModal');
            modal.classList.remove('modal-show');
            
            // 恢复背景滚动
            document.body.style.overflow = '';
            
            setTimeout(() => {
                modal.classList.remove('flex');
                modal.classList.add('hidden');
                selectedMatchId = null;
            }, 300);
        }

        // 加载所有战队数据和联赛 (编辑模式)
        async function loadTeamsDataForEdit() {
            try {
                console.log("加载编辑模式战队数据...");
                const response = await fetch(`${API_BASE_URL}/teams`);
                allTeams = await response.json();
                
                console.log("编辑模式原始团队数据:", allTeams);
                
                // 检查数据格式
                let uniqueLeagues = [];
                
                if (Array.isArray(allTeams) && allTeams.length > 0) {
                    // 如果是扁平的列表格式，需要按联赛分组
                    if (!allTeams[0].hasOwnProperty('teams')) {
                        // 提取所有唯一的联赛
                        uniqueLeagues = [...new Set(allTeams.map(team => team.league))];
                        
                        // 按联赛分组以便在其他地方使用
                        const leagueGroups = {};
                        allTeams.forEach(team => {
                            if (!leagueGroups[team.league]) {
                                leagueGroups[team.league] = {
                                    league: team.league,
                                    teams: []
                                };
                            }
                            leagueGroups[team.league].teams.push(team);
                        });
                        
                        // 保留原始数据
                        allTeamsFlat = [...allTeams];
                        // 分组后的数据
                        allTeams = Object.values(leagueGroups);
                    } else {
                        // 已经是分组格式，提取联赛名称
                        uniqueLeagues = allTeams.map(league => league.league);
                    }
                }
                
                console.log("编辑模式处理后的团队数据:", allTeams);
                console.log("编辑模式联赛列表:", uniqueLeagues);
                
                // 填充联赛下拉框
                const leagueSelect = document.getElementById('edit_league');
                if (leagueSelect) {
                    leagueSelect.innerHTML = `
                        <option value="" selected disabled hidden></option>
                        ${uniqueLeagues.map(league => `<option value="${league}">${league}</option>`).join('')}
                    `;
                }
                
                return true;
            } catch (error) {
                console.error('Error loading teams data for edit:', error);
                return false;
            }
        }
        
        // 根据选择的联赛加载战队 (编辑模式)
        function loadTeamsByLeagueForEdit(leagueName) {
            console.log("编辑模式加载联赛:", leagueName);
            // 找到选中的联赛对应的战队
            let selectedLeagueTeams = [];
            
            // 检查数据结构
            if (Array.isArray(allTeams)) {
                if (allTeams.length > 0 && allTeams[0].hasOwnProperty('teams')) {
                    // 分组结构
                    const selectedLeague = allTeams.find(league => league.league === leagueName);
                    if (selectedLeague && selectedLeague.teams) {
                        selectedLeagueTeams = selectedLeague.teams;
                    }
                } else {
                    // 扁平结构
                    selectedLeagueTeams = allTeams.filter(team => team.league === leagueName);
                }
            }
            
            console.log("找到的战队(编辑):", selectedLeagueTeams);
            
            if (selectedLeagueTeams.length > 0) {
                // 更新主队下拉框
                const team1Select = document.getElementById('edit_team1');
                team1Select.innerHTML = `
                    <option value="" selected disabled hidden></option>
                    ${selectedLeagueTeams.map(team => `<option value="${team.name}">${team.name}</option>`).join('')}
                `;
                
                // 更新客队下拉框
                const team2Select = document.getElementById('edit_team2');
                team2Select.innerHTML = `
                    <option value="" selected disabled hidden></option>
                    ${selectedLeagueTeams.map(team => `<option value="${team.name}">${team.name}</option>`).join('')}
                `;
                
                // 清空获胜方下拉框
                document.getElementById('edit_winner').innerHTML = `
                    <option value="" selected disabled hidden></option>
                `;
            }
        }

        // 更新编辑模态框的获胜方选择框
        function updateEditWinnerOptions() {
            const team1 = document.querySelector('#edit_team1').value;
            const team2 = document.querySelector('#edit_team2').value;
            const winnerSelect = document.querySelector('#edit_winner');
            
            winnerSelect.innerHTML = `
                <option value="" selected disabled hidden></option>
                ${team1 ? `<option value="${team1}">${team1}</option>` : ''}
                ${team2 ? `<option value="${team2}">${team2}</option>` : ''}
            `;
        }

        // 处理编辑表单提交时收集游戏详情
        document.getElementById('editMatchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            const matchId = data.id;
            delete data.id;
            
            // 收集游戏详情
            const games = [];
            const gameFields = document.querySelectorAll('#editGamesContainer .game-field');
            
            if (gameFields.length > 0) {
                gameFields.forEach(field => {
                    const fieldId = field.querySelector('input[name^="edit_game_id_"]').value;
                    const isBlue = field.querySelector(`#edit_game_blue_side_${fieldId}`).value === 'true';
                    const winnerSide = field.querySelector(`#edit_game_winner_side_${fieldId}`).value;
                    games.push({
                        game_number: parseInt(field.querySelector(`#edit_game_number_${fieldId}`).value),
                        blue_side: isBlue,
                        winner_side: winnerSide,
                        blue_team: isBlue ? data.team1 : data.team2,
                        red_team: isBlue ? data.team2 : data.team1,
                        investment: parseFloat(field.querySelector(`#edit_game_investment_${fieldId}`).value),
                        return_amount: parseFloat(field.querySelector(`#edit_game_return_${fieldId}`).value)
                    });
                });
            } else {
                // 如果没有添加单场比赛详情，自动生成
                const totalGames = data.match_format === 'Bo5' ? 5 : 3;
                const perGameInvestment = parseFloat(data.investment) / totalGames;
                const perGameReturn = parseFloat(data.return_amount) / totalGames;
                
                for (let i = 1; i <= totalGames; i++) {
                    const isBlue = i % 2 === 1 ? data.team1_blue_side === 'true' : data.team1_blue_side !== 'true';
                    games.push({
                        game_number: i,
                        blue_side: isBlue,
                        winner_side: data.winner === data.team1 ? 'blue' : 'red',
                        blue_team: isBlue ? data.team1 : data.team2,
                        red_team: isBlue ? data.team2 : data.team1,
                        investment: perGameInvestment,
                        return_amount: perGameReturn
                    });
                }
            }
            
            data.games = games;
            
            // 删除表单中不需要提交的数据
            for (const key in data) {
                if (key.startsWith('edit_game_')) {
                    delete data[key];
                }
            }
            
            try {
                const response = await fetch(`${API_BASE_URL}/matches/${matchId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    console.log("更新记录成功!");
                    hideEditModal();
                    loadMatches(); // 重新加载比赛列表
                } else {
                    const errorData = await response.json();
                    console.error("更新记录失败:", errorData);
                    alert("更新记录失败: " + (errorData.error || "未知错误"));
                }
            } catch (error) {
                console.error("更新记录时发生错误:", error);
                alert("更新记录时发生错误: " + error.message);
            }
        });

        // 删除比赛记录
        async function deleteMatch() {
            if (!selectedMatchId) return;
            
            // 显示自定义确认删除弹窗
            showConfirmDeleteModal();
        }
        
        // 显示确认删除弹窗
        function showConfirmDeleteModal() {
            const modal = document.getElementById('confirmDeleteModal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            setTimeout(() => {
                modal.classList.add('modal-show');
            }, 10);
        }
        
        // 隐藏确认删除弹窗
        function hideConfirmDeleteModal() {
            const modal = document.getElementById('confirmDeleteModal');
            modal.classList.remove('modal-show');
            setTimeout(() => {
                modal.classList.remove('flex');
                modal.classList.add('hidden');
            }, 300);
        }
        
        // 确认删除操作
        async function confirmDelete() {
            try {
                const response = await fetch(`${API_BASE_URL}/matches/${selectedMatchId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    hideConfirmDeleteModal();
                    hideEditModal();
                    loadMatches(); // 重新加载比赛列表
                }
            } catch (error) {
                console.error('Error deleting match:', error);
            }
        }

        // 筛选比赛记录
        function filterMatches(filter) {
            let filteredMatches = [];
            const today = new Date();
            
            switch (filter) {
                case 'all':
                    filteredMatches = allMatches;
                    break;
                case 'profit':
                    filteredMatches = allMatches.filter(match => 
                        match.return_amount > match.investment
                    );
                    break;
                case 'loss':
                    filteredMatches = allMatches.filter(match => 
                        match.return_amount <= match.investment
                    );
                    break;
                case 'week':
                    // 获取本周的第一天 (周一)
                    const firstDay = new Date(today);
                    firstDay.setDate(today.getDate() - today.getDay() + (today.getDay() === 0 ? -6 : 1));
                    firstDay.setHours(0, 0, 0, 0);
                    
                    filteredMatches = allMatches.filter(match => {
                        const matchDate = new Date(match.match_date);
                        return matchDate >= firstDay;
                    });
                    break;
                case 'month':
                    // 获取本月的第一天
                    const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
                    
                    filteredMatches = allMatches.filter(match => {
                        const matchDate = new Date(match.match_date);
                        return matchDate >= firstDayOfMonth;
                    });
                    break;
            }
            
            renderMatches(filteredMatches);
            
            // 更新筛选按钮样式
            document.querySelectorAll('.filter-btn').forEach(btn => {
                // 移除所有活跃状态
                btn.classList.remove('active', 'bg-blue-100', 'bg-green-50', 'bg-red-50', 'bg-gray-100');
                btn.classList.remove('text-blue-600', 'text-green-600', 'text-red-600', 'text-gray-600');
                btn.classList.add('bg-gray-100', 'text-gray-600');
                
                // 设置选中按钮的样式
                const buttonText = btn.textContent.trim();
                if (
                    (filter === 'all' && buttonText === '全部') ||
                    (filter === 'profit' && buttonText === '盈利') ||
                    (filter === 'loss' && buttonText === '亏损') ||
                    (filter === 'week' && buttonText === '本周') ||
                    (filter === 'month' && buttonText === '本月')
                ) {
                    btn.classList.add('active');
                    
                    // 为不同类型的按钮设置不同的活跃样式
                    if (filter === 'all') {
                        btn.classList.add('bg-blue-100', 'text-blue-600');
                    } else if (filter === 'profit') {
                        btn.classList.add('bg-green-50', 'text-green-600');
                    } else if (filter === 'loss') {
                        btn.classList.add('bg-red-50', 'text-red-600');
                    } else {
                        btn.classList.add('bg-blue-100', 'text-blue-600');
                    }
                    
                    btn.classList.remove('bg-gray-100', 'text-gray-600');
                }
            });
        }

        // 显示添加记录模态框
        function showAddMatchModal() {
            // 加载最新的战队和联赛数据
            loadTeamsData();
            
            const modal = document.getElementById('addMatchModal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
            
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
            
            setTimeout(() => {
                modal.classList.add('modal-show');
            }, 10);
        }

        // 隐藏添加记录模态框
        function hideAddMatchModal() {
            const modal = document.getElementById('addMatchModal');
            modal.classList.remove('modal-show');
            
            // 恢复背景滚动
            document.body.style.overflow = '';
            
            setTimeout(() => {
                modal.classList.remove('flex');
                modal.classList.add('hidden');
            }, 300);
        }

        // 处理添加记录表单提交
        document.getElementById('addMatchForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            console.log("提交表单...");
            
            const formData = new FormData(e.target);
            const data = Object.fromEntries(formData.entries());
            console.log("表单数据:", data);
            
            // 处理团队方位
            data.team1_blue_side = data.team1_blue_side === 'true';
            
            // 转换数值字段
            data.investment = parseFloat(data.investment);
            data.return_amount = parseFloat(data.return_amount);
            
            // 收集游戏详情
            const games = [];
            const gameFields = document.querySelectorAll('#gamesContainer .game-field');
            
            gameFields.forEach(field => {
                const fieldId = field.querySelector('input[name^="game_id_"]').value;
                const blueSide = field.querySelector(`#game_blue_side_${fieldId}`).value === 'true';
                const winnerSide = field.querySelector(`#game_winner_side_${fieldId}`).value;
                
                // 根据方位和获胜方确定获胜战队
                const blueTeam = blueSide ? data.team1 : data.team2;
                const redTeam = blueSide ? data.team2 : data.team1;
                const winnerTeam = winnerSide === 'blue' ? blueTeam : redTeam;
                
                games.push({
                    game_number: parseInt(field.querySelector(`#game_number_${fieldId}`).value),
                    blue_side: blueSide,
                    blue_team: blueTeam,
                    red_team: redTeam,
                    winner_side: winnerSide,
                    winner_team: winnerTeam,
                    investment: parseFloat(field.querySelector(`#game_investment_${fieldId}`).value),
                    return_amount: parseFloat(field.querySelector(`#game_return_${fieldId}`).value)
                });
            });
            
            // 如果没有添加单场比赛详情，自动生成
            if (games.length === 0) {
                const totalGames = data.match_format === 'Bo5' ? 5 : 3;
                const perGameInvestment = data.investment / totalGames;
                const perGameReturn = data.return_amount / totalGames;
                
                for (let i = 1; i <= totalGames; i++) {
                    const blueSide = i % 2 === 1 ? data.team1_blue_side : !data.team1_blue_side;
                    const blueTeam = blueSide ? data.team1 : data.team2;
                    const redTeam = blueSide ? data.team2 : data.team1;
                    const winnerTeam = data.winner;
                    const winnerSide = winnerTeam === blueTeam ? 'blue' : 'red';
                    
                    games.push({
                        game_number: i,
                        blue_side: blueSide,
                        blue_team: blueTeam,
                        red_team: redTeam,
                        winner_side: winnerSide,
                        winner_team: winnerTeam,
                        investment: perGameInvestment,
                        return_amount: perGameReturn
                    });
                }
            }
            
            data.games = games;
            
            try {
                console.log("发送API请求...");
                const response = await fetch(`${API_BASE_URL}/matches`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    console.log("添加记录成功!");
                    hideAddMatchModal();
                    loadMatches(); // 重新加载比赛列表
                    e.target.reset(); // 重置表单
                    // 重置日期时间为当前时间
                    const today = new Date();
                    today.setHours(0, 0, 0);
                    const dateString = today.toISOString().slice(0, 16);
                    document.querySelector('input[name="match_date"]').value = dateString;
                } else {
                    const errorData = await response.json();
                    console.error("添加记录失败:", errorData);
                    alert(`添加失败: ${errorData.message || '未知错误'}`);
                }
            } catch (error) {
                console.error('添加记录时发生错误:', error);
                alert('添加记录失败，请检查网络连接或稍后再试');
            }
        });

        // 加载所有战队数据和联赛
        async function loadTeamsData() {
            try {
                console.log("加载所有战队数据...");
                const response = await fetch(`${API_BASE_URL}/teams`);
                allTeams = await response.json();
                
                console.log("原始团队数据:", allTeams);
                
                // 检查数据格式
                let uniqueLeagues = [];
                
                if (Array.isArray(allTeams) && allTeams.length > 0) {
                    // 如果是扁平的列表格式，需要按联赛分组
                    if (!allTeams[0].hasOwnProperty('teams')) {
                        // 提取所有唯一的联赛
                        uniqueLeagues = [...new Set(allTeams.map(team => team.league))];
                        
                        // 按联赛分组以便在其他地方使用
                        const leagueGroups = {};
                        allTeams.forEach(team => {
                            if (!leagueGroups[team.league]) {
                                leagueGroups[team.league] = {
                                    league: team.league,
                                    teams: []
                                };
                            }
                            leagueGroups[team.league].teams.push(team);
                        });
                        
                        // 保留原始数据
                        allTeamsFlat = [...allTeams];
                        // 分组后的数据
                        allTeams = Object.values(leagueGroups);
                    } else {
                        // 已经是分组格式，提取联赛名称
                        uniqueLeagues = allTeams.map(league => league.league);
                    }
                }
                
                console.log("处理后的团队数据:", allTeams);
                console.log("联赛列表:", uniqueLeagues);
                
                // 填充联赛下拉框
                const leagueSelect = document.getElementById('league');
                if (leagueSelect) {
                    leagueSelect.innerHTML = `
                        <option value="" selected disabled hidden></option>
                        ${uniqueLeagues.map(league => `<option value="${league}">${league}</option>`).join('')}
                    `;
                }
            } catch (error) {
                console.error('Error loading teams data:', error);
            }
        }

        // 根据选择的联赛加载战队
        function loadTeamsByLeague(leagueName) {
            console.log("加载联赛:", leagueName);
            // 找到选中的联赛对应的战队
            let selectedLeagueTeams = [];
            
            // 检查数据结构
            if (Array.isArray(allTeams)) {
                if (allTeams.length > 0 && allTeams[0].hasOwnProperty('teams')) {
                    // 分组结构
                    const selectedLeague = allTeams.find(league => league.league === leagueName);
                    if (selectedLeague && selectedLeague.teams) {
                        selectedLeagueTeams = selectedLeague.teams;
                    }
                } else {
                    // 扁平结构
                    selectedLeagueTeams = allTeams.filter(team => team.league === leagueName);
                }
            }
            
            console.log("找到的战队:", selectedLeagueTeams);
            
            if (selectedLeagueTeams.length > 0) {
                // 更新主队下拉框
                const team1Select = document.getElementById('team1');
                team1Select.innerHTML = `
                    <option value="" selected disabled hidden></option>
                    ${selectedLeagueTeams.map(team => `<option value="${team.name}">${team.name}</option>`).join('')}
                `;
                
                // 更新客队下拉框
                const team2Select = document.getElementById('team2');
                team2Select.innerHTML = `
                    <option value="" selected disabled hidden></option>
                    ${selectedLeagueTeams.map(team => `<option value="${team.name}">${team.name}</option>`).join('')}
                `;
                
                // 清空获胜方下拉框
                document.getElementById('winner').innerHTML = `
                    <option value="" selected disabled hidden></option>
                `;
            }
        }

        // 更新获胜方选择框
        function updateWinnerOptions() {
            const team1 = document.querySelector('select[name="team1"]').value;
            const team2 = document.querySelector('select[name="team2"]').value;
            const winnerSelect = document.querySelector('select[name="winner"]');
            
            winnerSelect.innerHTML = `
                <option value="" selected disabled hidden></option>
                ${team1 ? `<option value="${team1}">${team1}</option>` : ''}
                ${team2 ? `<option value="${team2}">${team2}</option>` : ''}
            `;
        }

        // 切换游戏详情显示
        function toggleGameDetails(event, matchId) {
            event.stopPropagation(); // 阻止事件冒泡，防止触发长按
            
            const detailContainer = document.getElementById(`gameDetails-${matchId}`);
            const button = event.currentTarget;
            
            if (detailContainer.classList.contains('show')) {
                detailContainer.classList.remove('show');
                button.innerHTML = '<i class="fas fa-chevron-down"></i> 查看详情';
            } else {
                detailContainer.classList.add('show');
                button.innerHTML = '<i class="fas fa-chevron-up"></i> 收起详情';
            }
        }

        // 添加单场比赛详情字段
        function addGameField() {
            const gamesContainer = document.getElementById('gamesContainer');
            const matchFormat = document.getElementById('match_format').value;
            const gameCount = document.querySelectorAll('#gamesContainer .game-field').length + 1;
            
            // 限制游戏数量
            const maxGames = matchFormat === 'Bo5' ? 5 : 3;
            if (gameCount > maxGames) {
                alert(`Bo${maxGames}最多只能添加${maxGames}场比赛`);
                return;
            }
            
            const fieldId = Date.now(); // 使用时间戳作为唯一ID
            const gameField = document.createElement('div');
            gameField.className = 'game-field bg-gray-50 p-3 rounded-md mb-4';
            gameField.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h3 class="text-sm font-medium">第${gameCount}局比赛</h3>
                    <button type="button" onclick="removeGameField(this)" class="text-red-500 text-xs">
                        <i class="fas fa-times"></i> 移除
                    </button>
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div class="input-group mb-2">
                        <select name="game_blue_side_${fieldId}" id="game_blue_side_${fieldId}" required class="text-sm py-2">
                            <option value="true" selected>主队蓝方</option>
                            <option value="false">主队红方</option>
                        </select>
                        <label for="game_blue_side_${fieldId}" class="text-xs">方位</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="game_number_${fieldId}" id="game_number_${fieldId}" value="${gameCount}" placeholder=" " required class="text-sm py-2">
                        <label for="game_number_${fieldId}" class="text-xs">局数</label>
                    </div>
                    <div class="input-group mb-2">
                        <select name="game_winner_side_${fieldId}" id="game_winner_side_${fieldId}" required class="text-sm py-2">
                            <option value="blue" selected>蓝方获胜</option>
                            <option value="red">红方获胜</option>
                        </select>
                        <label for="game_winner_side_${fieldId}" class="text-xs">获胜方</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="game_investment_${fieldId}" id="game_investment_${fieldId}" step="0.01" placeholder=" " required class="text-sm py-2">
                        <label for="game_investment_${fieldId}" class="text-xs">投资额</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="game_return_${fieldId}" id="game_return_${fieldId}" step="0.01" placeholder=" " required class="text-sm py-2">
                        <label for="game_return_${fieldId}" class="text-xs">回报额</label>
                    </div>
                </div>
                <input type="hidden" name="game_id_${fieldId}" value="${fieldId}">
            `;
            
            gamesContainer.appendChild(gameField);
            
            // 自动滚动到新添加的字段
            setTimeout(() => {
                gameField.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }, 100);
        }
        
        // 移除游戏字段
        function removeGameField(button) {
            const gameField = button.closest('.game-field');
            gameField.remove();
            
            // 重新编号其他游戏字段
            const gameFields = document.querySelectorAll('#gamesContainer .game-field');
            gameFields.forEach((field, index) => {
                field.querySelector('h3').textContent = `第${index + 1}局比赛`;
                field.querySelector('input[name^="game_number_"]').value = index + 1;
            });
        }
        
        // 监听赛制变化
        document.getElementById('match_format').addEventListener('change', function() {
            const matchFormat = this.value;
            const maxGames = matchFormat === 'Bo5' ? 5 : 3;
            const gameFields = document.querySelectorAll('#gamesContainer .game-field');
            
            // 如果当前游戏数量超过新的最大值，删除多余的字段
            if (gameFields.length > maxGames) {
                for (let i = maxGames; i < gameFields.length; i++) {
                    gameFields[i].remove();
                }
            }
        });

        // 添加编辑模态框的游戏详情字段
        function addEditGameField() {
            const gamesContainer = document.getElementById('editGamesContainer');
            const matchFormat = document.getElementById('edit_match_format').value;
            const gameCount = document.querySelectorAll('#editGamesContainer .game-field').length + 1;
            
            // 限制游戏数量
            const maxGames = matchFormat === 'Bo5' ? 5 : 3;
            if (gameCount > maxGames) {
                alert(`Bo${maxGames}最多只能添加${maxGames}场比赛`);
                return;
            }
            
            const fieldId = Date.now(); // 使用时间戳作为唯一ID
            const gameField = document.createElement('div');
            gameField.className = 'game-field bg-gray-50 p-3 rounded-md mb-4';
            gameField.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <h3 class="text-sm font-medium">第${gameCount}局比赛</h3>
                    <button type="button" onclick="removeEditGameField(this)" class="text-red-500 text-xs">
                        <i class="fas fa-times"></i> 移除
                    </button>
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div class="input-group mb-2">
                        <select name="edit_game_blue_side_${fieldId}" id="edit_game_blue_side_${fieldId}" required class="text-sm py-2">
                            <option value="true" selected>主队蓝方</option>
                            <option value="false">主队红方</option>
                        </select>
                        <label for="edit_game_blue_side_${fieldId}" class="text-xs">方位</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="edit_game_number_${fieldId}" id="edit_game_number_${fieldId}" value="${gameCount}" placeholder=" " required class="text-sm py-2">
                        <label for="edit_game_number_${fieldId}" class="text-xs">局数</label>
                    </div>
                    <div class="input-group mb-2">
                        <select name="edit_game_winner_side_${fieldId}" id="edit_game_winner_side_${fieldId}" required class="text-sm py-2">
                            <option value="blue" selected>蓝方获胜</option>
                            <option value="red">红方获胜</option>
                        </select>
                        <label for="edit_game_winner_side_${fieldId}" class="text-xs">获胜方</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="edit_game_investment_${fieldId}" id="edit_game_investment_${fieldId}" step="0.01" placeholder=" " required class="text-sm py-2">
                        <label for="edit_game_investment_${fieldId}" class="text-xs">投资额</label>
                    </div>
                    <div class="input-group mb-2">
                        <input type="number" name="edit_game_return_${fieldId}" id="edit_game_return_${fieldId}" step="0.01" placeholder=" " required class="text-sm py-2">
                        <label for="edit_game_return_${fieldId}" class="text-xs">回报额</label>
                    </div>
                </div>
                <input type="hidden" name="edit_game_id_${fieldId}" value="${fieldId}">
            `;
            
            gamesContainer.appendChild(gameField);
            
            // 自动滚动到新添加的字段
            setTimeout(() => {
                gameField.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
            }, 100);
        }
        
        // 移除编辑模态框的游戏字段
        function removeEditGameField(button) {
            const gameField = button.closest('.game-field');
            gameField.remove();
            
            // 重新编号其他游戏字段
            const gameFields = document.querySelectorAll('#editGamesContainer .game-field');
            gameFields.forEach((field, index) => {
                field.querySelector('h3').textContent = `第${index + 1}局比赛`;
                field.querySelector('input[name^="edit_game_number_"]').value = index + 1;
            });
        }

        // 初始化时设置今天的日期作为默认值，并加载战队数据
        document.addEventListener('DOMContentLoaded', async () => {
            // 设置默认日期和时间
            const today = new Date();
            today.setHours(0, 0, 0);
            const dateString = today.toISOString().slice(0, 16); // 格式：YYYY-MM-DDTHH:MM
            document.querySelector('input[name="match_date"]').value = dateString;
            
            // 先加载战队数据，再加载比赛记录
            await loadTeamsData();
            loadMatches();
        });
    </script>
</body>
</html> 